<?php
/**
 * Minhlog Domain_Mapper 文章标签关系类
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 *
 * @category   Domain
 * @package    Domain_DataMapper
 * @copyright  Copyright (c) 2009-2010 Minh.Shu@gmail.com
 * @license    New BSD License
 * @author     Minh.Shu
 * @version    $Id: Article.php 2 2010-01-17 13:49:08Z Minh.Shu $
 *
 */

class Domain_DataMapper_Tag_Article extends Domain_DataMapper_Abstract
{
    protected $_tableClassName = 'Domain_Table_Tag_Article';

    protected $_dataMapper = array (
            'relationId' => 'relation_id',
            'articleId'  => 'article_id',
            'tagId'      => 'tag_id'
    );

    /**
     * 根据标签ID获取关联文章
     * @param integer $tagId
     * @return object|void
     */
    public function findRelationByTag($tagId)
    {
        return $this->getTable()->fetchAll($this->findRelationByTagStatement($tagId));
    }

    /**
     * 根据文章标签查询匹配关系
     * @param integer $articleId
     * @param integer $tagId
     * @return object|void
     */
    public function findTagRelation($articleId, $tagId)
    {
        return $this->getTable()->fetchRow($this->checkTagRelationStatement($articleId, $tagId));
    }

    /**
     * 封装根据标签ID获取关联文章SQL
     * @param integer $tagId
     * @return Zend_Db_Table_Select
     */
    private function findRelationByTagStatement($tagId)
    {
        $db = $this->getTable()->getAdapter();
        $select = $this->getTable()->select();
        $select->where($db->quoteInto('tag_id = ?',$tagId))
                ->order('relation_id DESC');
        return $select;
    }

    /**
     * 封装根据文章标签查询匹配关系SQL
     * @param integer $articleId
     * @param integer $tagId
     * @return Zend_Db_Table_Select
     */
    private function checkTagRelationStatement($articleId, $tagId)
    {
        $db = $this->getTable()->getAdapter();
        $select = $this->getTable()->select();
        $select->where($db->quoteInto('article_id = ?',$articleId))
                ->where($db->quoteInto('tag_id = ?',$tagId))
                ->limit(1);
        return $select;
    }

}